package com.superf.taobao.service;

import com.superf.taobao.entity.Book;
import com.superf.taobao.entity.CartItem;
import com.superf.taobao.entity.ShoppingCart;
import com.superf.taobao.util.BookUtil;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import java.util.Set;

public class ShowAllBooksServlet extends HttpServlet{
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        HttpSession session = req.getSession(false);
        if(session == null || session.getAttribute("user")==null){
            resp.sendRedirect(req.getContextPath()+"/login.html");
            return;
        }

        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out = resp.getWriter();// 得到字符输出流
        out.write("热门图书列表:<br>");
        Map<String, Book> booksMap = BookUtil.findAllBooks();
        Set<Map.Entry<String, Book>> entrys = booksMap.entrySet();
        for (Map.Entry<String, Book> entry : entrys) {
            Book book = entry.getValue();
            out.write("<a href='"+req.getContextPath()+"/showDetail?id="+book.getId()+"'>"+book.getName()+"</a>");
            out.write("&nbsp;&nbsp;&nbsp;<a href='" + req.getContextPath() + "/buy?id=" + book.getId()
                    + "'>添加到购物车</a><br>");
        }

        out.write("<hr>");
        out.write("浏览过的书:<br>");
        //读取cookie
        Cookie[] cookies = req.getCookies();
        if(cookies==null){
            out.write("没有浏览过图书:<br>");
        }else{
            for(Cookie cookie:cookies){
                if(cookie.getName().equals("histroyrecord")){
                    String value=cookie.getValue();//得到拼接好的字符串
                    String [] ids = value.split("-");
                    for(String id:ids){
                        out.write(BookUtil.findBookById(id).toString()+"<br>");
                    }
                }
            }
        }

        out.write("<hr>");
        out.write("购物车明细:<br>");
        // 从购物车中遍历数据
//        HttpSession session = req.getSession();
        ShoppingCart cart = (ShoppingCart) session.getAttribute("cart");
        if (cart == null || cart.getSize() == 0) {
            out.write("没有购买商品<br>");
        } else {
            Map<String, CartItem> map = cart.getCart();
            Set<Map.Entry<String, CartItem>> items = map.entrySet();
            for (Map.Entry<String, CartItem> item : items) {
                CartItem cartItem = item.getValue();
                out.write(cartItem.getBook().toString()+",数量:"+cartItem.getAmount()+"<br/>");
            }
            out.write("总金额:"+cart.getTotalPrice());
        }
        out.close();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
